package dhy.com.tomcat.three.core.connector;

import dhy.com.tomcat.three.core.porcessor.HttpProcessor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @author 大忽悠
 * @create 2022/3/9 17:55
 */
public class HttpConnector implements Runnable{
    /**
     * tomcat是否停止
     */
    private boolean stopped;
    /**
     * 通信使用的协议
     */
    private String scheme="http";
    /**
     * 默认服务器端口号
     */
    private static final Integer DEFAULT_PORT=80;

    /**
     * 创建一个新的线程，启动连接器
     */
    public void start() {
        new Thread(this,"dhy-connector-01").start();
    }


    public String getScheme() {
        return scheme;
    }



    @Override
    public void run() {
        ServerSocket serverSocket=null;
        try {
            //backlog设置连接队列大小,当队列中未处理的连接数超过backlog后,服务器会拒绝此次连接
            serverSocket=new ServerSocket(DEFAULT_PORT);
        } catch (IOException e) {
            e.printStackTrace();
            //通常: 0表示正常退出,1表示异常退出
            System.exit(1);
        }
        //循环等待客户端连接
        while(!stopped)
        {
            try {
                Socket socket = serverSocket.accept();
                //TODO:后期线程池优化处理
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //处理客户端连接请求
                        doHandleAccept(socket);
                    }
                },"dhy-processor-"+ UUID.randomUUID().toString().substring(0,5)).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("服务器已断开连接");
    }

    private void doHandleAccept(Socket socket) {
        try{
            System.out.println("当前线程: "+Thread.currentThread().getName());
            System.out.println("客户端已接入");
            //处理客户端连接请求
            //与上节的不同之处，不从连接器中直接判断请求类型，而是交给HttpProcessor处理
            HttpProcessor processor=new HttpProcessor(this);
            processor.process(socket);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

